import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

import { ElMessage } from 'element-plus'

import qs from 'qs'

import { config } from '@/config/axios/config'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { resetRouter } from '@/router'
import { getBackEndMsg } from '@/utils'

const appStore = useAppStore()
const { result_code, base_url } = config
const tagsViewStore = useTagsViewStore()
const { wsCache } = useCache()
export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH] + 'ezlcp/'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const headers = config.headers as AxiosRequestHeaders

    if (
      config.method === 'post' &&
      headers['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }

    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    //缓存中有token，header中加入token
    const { wsCache } = useCache()
    if (wsCache.get(appStore.getUserInfo)) {
      const userData = wsCache.get(appStore.getUserInfo)
      headers.token = userData.data.token
    }
    headers.PathName = location.pathname
    return config
  },
  (error: AxiosError) => {
    console.log(error)
    Promise.reject(error)
  }
)
// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<Recordable>) => {
    let message
    if (response.data.code == result_code) {
      //是否提醒报错信息
      if (response.data.show) {
        ElMessage.closeAll()
        message = getBackEndMsg(response.data.message, '')
        setTimeout(() => {
          ElMessage.success(message)
        }, 100)
      }
      return response.data
    } else {
      message = getBackEndMsg(response.data.message, response.data.data)
      ElMessage.closeAll()
      setTimeout(() => {
        ElMessage.error(message)
      }, 100)
    }
  },
  (error: AxiosError) => {
    const resp = error.response as any
    const data = resp.data as any
    //token失效，重新登录
    if (data.code == 401) {
      wsCache.clear()
      tagsViewStore.delAllViews()
      resetRouter() // 重置静态路由表
      const message = getBackEndMsg(data.message, data.data)
      ElMessage.warning(message)
      setTimeout(() => {
        location.href = '/login'
      }, 4000)
      return
    }
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

export { service }
